package utils

import (
	"bytes"
	"text/template"

	devcontainer_apps_v1 "devstar.cn/DevcontainerApp/api/v1"
	app_v1 "k8s.io/api/apps/v1"
	core_v1 "k8s.io/api/core/v1"
	yaml_util "k8s.io/apimachinery/pkg/util/yaml"
)

const (
	TemplatePath = "internal/controller/templates/"
)

// parseTemplate 解析 Go Template 模板文件
func parseTemplate(templateName string, app *devcontainer_apps_v1.DevcontainerApp) []byte {
	tmpl, err := template.
		New(templateName + ".yaml").
		Funcs(template.FuncMap{"default": DefaultFunc}).
		ParseFiles(TemplatePath + templateName + ".yaml")
	if err != nil {
		panic(err)
	}
	b := new(bytes.Buffer)
	err = tmpl.Execute(b, app)
	if err != nil {
		panic(err)
	}
	return b.Bytes()
}

// NewStatefulSet 创建 StatefulSet
func NewStatefulSet(app *devcontainer_apps_v1.DevcontainerApp) *app_v1.StatefulSet {
	statefulSet := &app_v1.StatefulSet{}
	err := yaml_util.Unmarshal(parseTemplate("statefulset", app), statefulSet)
	if err != nil {
		panic(err)
	}
	return statefulSet
}

// NewService 创建 Service
func NewService(app *devcontainer_apps_v1.DevcontainerApp) *core_v1.Service {
	service := &core_v1.Service{}
	err := yaml_util.Unmarshal(parseTemplate("service", app), service)
	if err != nil {
		panic(err)
	}
	return service
}

// DefaultFunc 函数用于实现默认值
func DefaultFunc(value interface{}, defaultValue interface{}) interface{} {
	if value == nil || value == "" {
		return defaultValue
	}
	return value
}
